<template>
  <div class="app-container">
    <YearMonthSelector v-model="queryParams.reportingYearMonth" @change="handleYearMonthChange" />

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证件类型代码" prop="idTypeCode">
        <el-select v-model="queryParams.idTypeCode" placeholder="请选择身份证件类型代码" clearable>
          <el-option
            v-for="dict in id_type_code"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="身份证件号码" prop="idNumber">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入身份证件号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别代码" prop="genderCode">
        <el-select v-model="queryParams.genderCode" placeholder="请选择性别代码" clearable>
          <el-option
            v-for="dict in gender_code"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="民族代码" prop="ethnicityCode">
        <el-select v-model="queryParams.ethnicityCode" placeholder="请选择民族代码" clearable>
          <el-option
            v-for="dict in ethnicity_code"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="现居地址" prop="currentAddress">
        <el-input
          v-model="queryParams.currentAddress"
          placeholder="请输入现居地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="户籍地" prop="householdAddress">
        <el-input
          v-model="queryParams.householdAddress"
          placeholder="请输入户籍地"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出生日期" prop="birthDate">
        <el-date-picker clearable
          v-model="queryParams.birthDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择出生日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="婚姻状况" prop="maritalStatus">
        <el-select v-model="queryParams.maritalStatus" placeholder="请选择婚姻状况" clearable>
          <el-option
            v-for="dict in marital_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['report:ex_offender:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['report:ex_offender:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['report:ex_offender:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['report:ex_offender:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="success"
          plain
          @click="handleReport"
        >立即上报</el-button>
      </el-col>
      <el-col :span="1.5" v-else>
        <el-button
          type="info"
          plain
          disabled
        >已上报</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ex_offenderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="身份证件类型代码" align="center" prop="idTypeCode">
        <template #default="scope">
          <dict-tag :options="id_type_code" :value="scope.row.idTypeCode"/>
        </template>
      </el-table-column>
      <el-table-column label="身份证件号码" align="center" prop="idNumber" />
      <el-table-column label="性别代码" align="center" prop="genderCode">
        <template #default="scope">
          <dict-tag :options="gender_code" :value="scope.row.genderCode"/>
        </template>
      </el-table-column>
      <el-table-column label="民族代码" align="center" prop="ethnicityCode">
        <template #default="scope">
          <dict-tag :options="ethnicity_code" :value="scope.row.ethnicityCode"/>
        </template>
      </el-table-column>
      <el-table-column label="现居地址" align="center" prop="currentAddress" />
      <el-table-column label="户籍地" align="center" prop="householdAddress" />
      <el-table-column label="出生日期" align="center" prop="birthDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="婚姻状况" align="center" prop="maritalStatus">
        <template #default="scope">
          <dict-tag :options="marital_status" :value="scope.row.maritalStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="reportStatus === '0'">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['report:ex_offender:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['report:ex_offender:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改刑满释放人员对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ex_offenderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证件类型代码" prop="idTypeCode">
          <el-select v-model="form.idTypeCode" placeholder="请选择身份证件类型代码">
            <el-option
              v-for="dict in id_type_code"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证件号码" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入身份证件号码" />
        </el-form-item>
        <el-form-item label="性别代码" prop="genderCode">
          <el-select v-model="form.genderCode" placeholder="请选择性别代码">
            <el-option
              v-for="dict in gender_code"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="民族代码" prop="ethnicityCode">
          <el-select v-model="form.ethnicityCode" placeholder="请选择民族代码">
            <el-option
              v-for="dict in ethnicity_code"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="现居地址" prop="currentAddress">
          <el-input v-model="form.currentAddress" placeholder="请输入现居地址" />
        </el-form-item>
        <el-form-item label="户籍地" prop="householdAddress">
          <el-input v-model="form.householdAddress" placeholder="请输入户籍地" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker clearable
            v-model="form.birthDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="婚姻状况" prop="maritalStatus">
          <el-select v-model="form.maritalStatus" placeholder="请选择婚姻状况">
            <el-option
              v-for="dict in marital_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Ex_offender">
import { listEx_offender, getEx_offender, delEx_offender, addEx_offender, updateEx_offender } from "@/api/report/ex_offender"
import { getMonthlyReportStatusDetail, addReportRecord } from "@/api/report/monthlyReportStatus"
import YearMonthSelector from "@/components/YearMonthSelector/index.vue";

const { proxy } = getCurrentInstance()
const { marital_status, id_type_code, gender_code, ethnicity_code } = proxy.useDict('marital_status', 'id_type_code', 'gender_code', 'ethnicity_code')

const ex_offenderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const reportStatus = ref("0") // 默认未上报

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    idTypeCode: null,
    idNumber: null,
    genderCode: null,
    ethnicityCode: null,
    currentAddress: null,
    householdAddress: null,
    birthDate: null,
    maritalStatus: null,
    reportingYearMonth: null
  },
  rules: {
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    idTypeCode: [
      { required: true, message: "身份证件类型代码不能为空", trigger: "change" }
    ],
    idNumber: [
      { required: true, message: "身份证件号码不能为空", trigger: "blur" }
    ],
    genderCode: [
      { required: true, message: "性别代码不能为空", trigger: "change" }
    ],
    ethnicityCode: [
      { required: true, message: "民族代码不能为空", trigger: "change" }
    ],
    currentAddress: [
      { required: true, message: "现居地址不能为空", trigger: "blur" }
    ],
    householdAddress: [
      { required: true, message: "户籍地不能为空", trigger: "blur" }
    ],
    birthDate: [
      { required: true, message: "出生日期不能为空", trigger: "blur" }
    ],
    maritalStatus: [
      { required: true, message: "婚姻状况不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询刑满释放人员列表 */
function getList() {
  loading.value = true
  // 确保携带 reportingYearMonth 参数
  if (!queryParams.value.reportingYearMonth) {
    const now = new Date()
    queryParams.value.reportingYearMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
  }

  // 获取上报状态
  getReportStatus()

  listEx_offender(queryParams.value).then(response => {
    ex_offenderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 获取上报状态
function getReportStatus() {
  const tableName = "ex_offender"
  const reportYearMonth = queryParams.value.reportingYearMonth
  if (reportYearMonth) {
    getMonthlyReportStatusDetail(tableName, reportYearMonth).then(response => {
      reportStatus.value = response.data.isReported
    }).catch(() => {
      // 如果获取失败，默认为未上报
      reportStatus.value = "0"
    })
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    idTypeCode: null,
    idNumber: null,
    genderCode: null,
    ethnicityCode: null,
    currentAddress: null,
    householdAddress: null,
    birthDate: null,
    maritalStatus: null,
    reportingYearMonth: queryParams.value.reportingYearMonth
  }
  proxy.resetForm("ex_offenderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加刑满释放人员"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getEx_offender(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改刑满释放人员"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ex_offenderRef"].validate(valid => {
    if (valid) {
      // 确保传递 reportingYearMonth 字段
      form.value.reportingYearMonth = queryParams.value.reportingYearMonth;
      if (form.value.id != null) {
        updateEx_offender(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addEx_offender(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除刑满释放人员编号为"' + _ids + '"的数据项？').then(function() {
    return delEx_offender(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('report/ex_offender/export', {
    ...queryParams.value
  }, `ex_offender_${new Date().getTime()}.xlsx`)
}

/** 上报按钮操作 */
function handleReport() {
  proxy.$modal.confirm('确定要上报数据吗？上报后数据将不可修改！').then(() => {
    const reportData = {
      tableName: "ex_offender",
      reportYearMonth: queryParams.value.reportingYearMonth
    }

    return addReportRecord(reportData)
  }).then(response => {
    if (response.data === 1) {
      proxy.$modal.msgSuccess("上报成功")
      // 更新上报状态为已上报
      reportStatus.value = "1"
    } else {
      proxy.$modal.msgError("上报失败")
    }
  }).catch(error => {
    if (error !== 'cancel') {
      proxy.$modal.msgError("上报失败: " + error.message)
    }
  })
}

// 年月选择变化处理
function handleYearMonthChange() {
  getList()
}

getList()
</script>
